// 实现这个项目的构建任务
const { series ,parallel ,src ,dest, watch } = require('gulp')
const loadPlugins = require('gulp-load-plugins')
const sass = require('gulp-sass')(require('sass'));
const del = require('del')
const plugins = loadPlugins()
const browserSync = require('browser-sync')
const bs = browserSync.create()
const scripts = ()=>{
    return src('src/assets/scripts/main.js',{base: 'src'})
            .pipe(plugins.babel({presets: ['@babel/preset-env']}))
            .pipe(dest('temp'))
            .pipe(bs.reload({stream: true}))
}
const css = ()=>{
    return src('src/assets/styles/**.scss',{base: 'src'})
            .pipe(sass())
            .pipe(dest('temp'))
            .pipe(bs.reload({stream: true}))

}

const html = ()=>{
    return src('src/**.html')
            .pipe(plugins.swig())
            .pipe(dest('temp'))
            .pipe(bs.reload({stream: true}))

}
const images = ()=>{
    return src('src/assets/images/**',{base: 'src'})
            .pipe(plugins.imagemin())
            .pipe(dest('dist'))
}
const fonts = ()=>{
    return src('src/assets/fonts/**',{base: 'src'})
            .pipe(plugins.imagemin())
            .pipe(dest('dist'))
}
const extra = ()=>{
    return src('public/**')
            .pipe(dest('dist'))
}
const clean = ()=>{
    return del(['dist','temp'])
} 
const useref = ()=>{
    return src('temp/*.html')
            .pipe(plugins.useref({
                searchPath: ['temp','.']
            }))
            .pipe(plugins.if(/\.js$/, plugins.uglify()))
            .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
            .pipe(plugins.if(/\.html$/, plugins.htmlmin({
                collapseWhiteSpace:true,
                minifyJs: true,
                minifyCss: true
            })))
            .pipe(dest('dist'))
}
const server = ()=>{
    watch('src/**.html',html)
    watch('src/assets/scripts/**.js',scripts)
    watch('src/assets/styles/**.scss',css)
    watch(['src/assets/images/**', 'src/assets/fonts/**', 'public/**'], bs.reload)
    return bs.init({
        server: {
            // files:'temp/**',
            baseDir:['temp','src', 'public'],
            router:{
                '/node_modules':'node_modules'
            }
        }
    })
}
const deploy = done=>{
    if (process.argv.includes('--production')){
        console.log('npm publish')
    }else {
        console.log('npm link')
    }
    done()
}
const compile = parallel(css, scripts, html)
const start = series(clean, compile, server)
const build = series(clean, parallel(series(compile, useref), fonts, extra))
module.exports = {
    clean,
    server,
    build,
    start,
    deploy
}